<template>
	<view>
		<view class="page__content">
			<z-paging ref="pagePaging" refresher-only @onRefresh="onRefresh" @scrolltolower="scrolltolower">
				<template #top>
					<view class="nav">
						<up-navbar :fixed="false" title="报工列表" :autoBack="false" leftIcon=" " :safeAreaInsetTop="true"
							leftIconColor="#fff">
						</up-navbar>
					</view>
				</template>

				<!-- 数据看板 -->
				<view class="KanbanBox">
					<view class="Kanban_CardBox" v-for="(item,index) in KanbanListData" :key="index"
						:style="{background:item.BackgroundColor}">
						<text>{{item.TextName}}</text>

						<view class="Kanban_CardBox_Value">
							{{item.Value}}
						</view>

						<!-- 样式A -->
						<view class="Style_A"></view>

						<!-- 样式B -->
						<view class="Style_B">
							<view class="Style_B_Round1">
								<view class="Style_B_Round2"></view>
							</view>
						</view>
					</view>
				</view>


				<!-- 吸顶Tab栏 -->
				<view>
					<view class="sticky-box" style="z-index: 100;position: sticky;top :0;">

						<z-tabs ref="tabs" unit="rpx" scroll-count="3" active-color="#51d0d0" :current="currTabIndex"
							:list="tabList" @change="changeTab">
							<template #right>
								<view class="x-f" style="padding-left: 4px;padding-right: 15px;">
									<uni-icons fontFamily="CustomFontPlatform"
										style="margin-left: 14px;font-weight: 600;" color="#999" @click="onRefresh"
										size="40rpx">{{uni.$utils.toUniCode('&#xe61c;')}}</uni-icons>

									<uni-icons fontFamily="CustomFontPlatform"
										style="margin-left: 14px;font-weight: 600;" color="#999" @click="OpenSortPopup"
										:class="sortData.Sort.value.toLowerCase() == 'desc' ? '' : 'icon-flip-vertical'"
										size="40rpx">{{ uni.$utils.toUniCode('&#xe7e9;')}}</uni-icons>

									<uni-icons fontFamily="CustomFontPlatform"
										style="margin-left: 14px;font-weight: 600;" color="#999" @click="rightClick"
										size="40rpx">{{uni.$utils.toUniCode('&#xe628;')}}</uni-icons>
								</view>
							</template>
						</z-tabs>

					</view>

					<swiper class="swiper" :style="[{height:swiperHeight+'px'}]" :current="currTabIndex"
						@transition="swiperTransition" @animationfinish="swiperAnimationfinish">
						<swiper-item class="swiper-item" v-for="(item, index) in tabList" :key="index">
							<sticky-swiper-next-item ref="swiperList" :tabIndex="index" :currentIndex="currTabIndex"
								:filterConfig="filterConfig" @heightChanged="heightChanged">
							</sticky-swiper-next-item>
						</swiper-item>
					</swiper>
				</view>


				<template #bottom>
					<view class="tabbar-box">
						<mc-tabbar style="width: 100%;" :current-page="currentID"></mc-tabbar>
					</view>
				</template>
			</z-paging>




		</view>

		<!-- 悬浮按钮_新增 -->
		<m-drag-button :isDock="true" :existTabBar="true" :initialBottom="80" @btnClick="ToAddWorkBtn">
			<template #BtnContent>
				<u-icon name="plus" color="#fff" size="54rpx"></u-icon>
			</template>
		</m-drag-button>

		<!-- 筛选弹层 -->
		<uni-popup ref="popup_filter" class="MainPopup" type="right" background-color="#ffffff"
			@close="closeFilterPopup">
			<view class="popup__content" style="width: 80vw;height: 100vh;">
				<up-navbar :fixed="false" title="筛选" :autoBack="false" leftIcon=" " :safeAreaInsetTop="true"
					leftIconColor="#fff" style="width: 100%;">
					<view class="u-nav-slot" slot="right">
						<uni-icons color="#fff" type="close" size="30" @click="closeFilterPopup"></uni-icons>
					</view>
				</up-navbar>

				<view class="popup__content__main f-dc FilterMainBox" style="background-color: #fff;">

					<view class="popup__content__main__section">
						<view class="popup__content__main__section__title">
							<text>单据日期</text>
						</view>
						<view class="popup__content__main__section__content">

							<view class="Select_Box">
								<view class="x-f Select_Date" v-for="(item,index) in DateList" :key="index"
									:class="[selectData == index ? 'Select_Date_Active' : '']"
									@click="SelectDateFun(item,index)">
									<text>{{item.Text}}</text>
									<text>{{item.nums}}</text>
								</view>

								<view class="ChoiceTimesBox" v-if="selectData == 5">

									<!-- <u-icon name="calendar" color="#999" size="20"></u-icon> -->


									<view class="TimeBox">

										<view class="StartTime timer" @click="ChoiceTime('start')">
											<text>开始时间</text>
											<text class="Date_Text">{{dateFormat(FilterFormData.StartTime)}}</text>
										</view>

										<view class="Icon">
											<u-icon name="minus" size="30"></u-icon>
										</view>

										<view class="EndTime timer" @click="ChoiceTime('end')">
											<text>结束时间</text>
											<text class="Date_Text">{{dateFormat(FilterFormData.EndTime)}}</text>
										</view>
									</view>
								</view>
							</view>
						</view>
					</view>

					<template v-if="!currTabIndex">
						<view class="popup__content__main__section">
							<view class="popup__content__main__section__title">
								<text>是否超时</text>
							</view>
							<view class="popup__content__main__section__content">
								<m-radio :options="radioOptions" :flexRow="true" v-model:value="FilterFormData.Timeout"
									borderRadius="9999px" contentActiveColor="#e1f7f8" contentActiveTextColor="#51d0d0"
									shape="square" fontSize="24rpx" @change="handleRadioChange"></m-radio>
							</view>
						</view>
					</template>

					<view class="popup__content__main__section">
						<view class="popup__content__main__section__title">
							<text>车间</text>
						</view>
						<view class="popup__content__main__section__content">
							<view @click="openSelectScreen('车间')">
								<up-input placeholder="请选择" v-model="FilterFormData.FWorkshopName" readonly
									border="bottom" suffixIcon="arrow-right" suffixIconStyle="color: #999"></up-input>
							</view>
						</view>
					</view>


					<view class="popup__content__main__section">
						<view class="popup__content__main__section__title">
							<text>物料信息</text>
						</view>
						<view class="popup__content__main__section__content">
							<view @click="openSelectScreen('物料')">
								<up-input placeholder="请选择" v-model="FilterFormData.ProductName" readonly
									border="bottom" suffixIcon="arrow-right" suffixIconStyle="color: #999"></up-input>
							</view>
						</view>
					</view>

					<view class="popup__content__main__section">
						<view class="popup__content__main__section__title">
							<text>工序</text>
						</view>
						<view class="popup__content__main__section__content">
							<view @click="openSelectScreen('工序')">
								<up-input placeholder="请选择" v-model="FilterFormData.ProcedureName" readonly
									border="bottom" suffixIcon="arrow-right" suffixIconStyle="color: #999"></up-input>
							</view>
						</view>
					</view>

					<view class="popup__content__main__section">
						<view class="popup__content__main__section__title">
							<text>作业员</text>
						</view>
						<view class="popup__content__main__section__content">
							<view @click="openSelectScreen('作业员')">
								<up-input placeholder="请选择" v-model="FilterFormData.EmplName" readonly border="bottom"
									suffixIcon="arrow-right" suffixIconStyle="color: #999"></up-input>
							</view>
						</view>
					</view>

				</view>

				<view class="page__content__bottom x-f" :style="uni.$utils.disposeSafeBottomFun()">
					<button class="content_bottom_primary_plainBtn CommonBtnSize" @click="ResetFilterBtn">重置</button>
					<button class="content_bottom_primary_Btn CommonBtnSize" @click="ComfirmFilterBtn">筛选</button>
				</view>
			</view>
		</uni-popup>

		<!-- 排序弹层 -->
		<uni-popup ref="popup_sort" type="bottom" background-color="#ffffff" @close="closeSortPopup">
			<view class="f-dc" style="max-height: 80vh;" :style="uni.$utils.disposeSafeBottomFun()">
				<up-navbar :fixed="false" title="排序" :autoBack="false" leftIcon=" " :safeAreaInsetTop="false"
					leftIconColor="#fff" style="width: 100%;">
					<view class="u-nav-slot" slot="right">
						<uni-icons color="#fff" type="close" size="30" @click="closeSortPopup"></uni-icons>
					</view>
				</up-navbar>

				<view class="MainBox" style="padding: 15px;flex: 1;overflow: auto;padding-bottom: 20px;">
					<m-sort :sortOptions="sortOptions" :defaultSort="defaultSort" :selectSort="sortData.Sort"
						@change="handleSortChange"></m-sort>
				</view>
			</view>
		</uni-popup>

		<!-- 时间选择器 -->
		<u-datetime-picker class="DateTimerPick" ref="datetimePicker" :title="PickerTitle" :show="showTimePicker"
			v-model="DatetimeData" mode="date" :closeOnClickOverlay="true" @close="ClosePicker" @cancel="ClosePicker"
			@confirm="ConfirmTime" :formatter="formatter"></u-datetime-picker>
	</view>
</template>

<script setup lang="ts">
	import { ref, reactive, onMounted, computed, getCurrentInstance } from 'vue'
	import { onLoad, onReady, onShow, onUnload } from '@dcloudio/uni-app'
	import useRequestQueue from '@/uni_modules/mc-ui/libs/http/UniversalRequestQueue';
	const { request, requestByUrl, PromiseRequestByUrl, onAllComplete, onError } = useRequestQueue();
	import { useMainStore, useUserStore, usePermissionStore, useTicketStore } from '@/store';
	const mainStore = useMainStore();
	const userStore = useUserStore();
	const permissionStore = usePermissionStore();
	const ticketStore = useTicketStore();

	import stickySwiperNextItem from '../components/sticky-swiper-next-item/sticky-swiper-next-item';
	import mcTabbar from '../components/mc-tabbar/mc-tabbar';
	// import zTabs from '../components/z-tabs/z-tabs';
	// import mRadio from '../components/m-radio/m-radio';

	defineOptions({
		options: {
			styleIsolation: 'shared'
		}
	})

	const FCJType = computed(() => {
		return ticketStore.FCJType;
	})

	let DatetimeData = ref<number>(Date.now());
	let showTimePicker = ref(false);
	let TimeType = ref('');
	let PickerTitle = ref('');

	const radioOptions = ref<any>([
		{ content: '全部', id: 0 },
		{ content: '未超时', id: 1 },
		{ content: '超时', id: 2 }
	]);

	let FilterFormData = reactive<any>({
		StartTime: new Date(),
		EndTime: new Date(),
		Timeout: 0,
		FWorkshopData: [],
		FWorkshopName: '',
		ProductData: [],
		ProductName: '',
		ProcedureData: [],
		ProcedureName: '',
		EmplData: [],
		EmplName: ''
	});

	let ShowTimePopup = ref(false);	// 选择时间弹层
	let DateList = ref<any>([
		{
			Text: '今天',
			nums: null,
			id: 1,
		},
		{
			Text: '昨天',
			nums: null,
			id: 2,
		},
		{
			Text: '本月',
			nums: null,
			id: 3,
		},
		{
			Text: '上月',
			nums: null,
			id: 4,
		},
		{
			Text: '全部',
			nums: null,
			id: 5,
		}, {
			Text: '自定义时间',
			nums: null,
			id: 6,
		}
	]);

	// 默认选中项
	let selectData = ref(0);
	// 选中数据
	let SelectDateItem = reactive({
		Text: '今天',
		nums: null,
		id: 1
	})

	interface KanbanItem {
		TextName : string;
		Value : string;
		BackgroundColor : string;
	}
	// 看板数据
	let KanbanListData = reactive<KanbanItem[]>([
		{
			TextName: '报工单数量',
			Value: '0',
			BackgroundColor: '#47aaff',
		},
		{
			TextName: '合格率',
			Value: '0.00%',
			BackgroundColor: '#43d489',
		},
		{
			TextName: '合格总数',
			Value: '0',
			BackgroundColor: '#fbb030',
		},
		{
			TextName: '不合格总数',
			Value: '0',
			BackgroundColor: '#ff6a52',
		},
	]);

	let tabList = ref<any>([{
		name: '未审核',
		value: null,
		badge: {
			count: null,
		}
	},
	{
		name: '已审核',
		value: null,
		badge: {
			count: null,
		}
	}]);

	let currTabIndex = ref(0);
	function changeTab(index : number) {	// 切换tab任务
		_setCurrent(index);
	}

	function _setCurrent(current : number) {
		if (current !== currTabIndex.value) {
			//切换tab时，将上一个tab的数据清空
			swiperList.value[currTabIndex.value].clear();
		}
		currTabIndex.value = current;
	}


	const instance = getCurrentInstance() as any;
	const query = uni.createSelectorQuery().in(instance.proxy);
	// 获取swiperHeight
	let swiperHeight = ref(0);
	const sysDeviceInfo = mainStore.systemConfig.sysDeviceInfo;


	let tabs = ref<any>(null);
	// swiper滑动中
	const swiperTransition = (e : any) => {
		tabs.value.setDx(e.detail.dx);
	}
	// swiper滑动结束
	const swiperAnimationfinish = (e : any) => {
		_setCurrent(e.detail.current);
		tabs.value.unlockDx();
	};
	// 设置swiper的高度
	const heightChanged = (height : any) => {
		if (height === 0) {
			query.select('.nav').fields({
				size: true
			}, (nav : any) => {
				swiperHeight.value = sysDeviceInfo.windowHeight - uni.upx2px(nav.height);

			})
		} else {
			swiperHeight.value = height;
		}
	}

	let pagePaging = ref<any>(null);
	let swiperList = ref<any>(null);



	// 当滚动到底部时，通知当前显示的列表加载更多
	function scrolltolower() {
		swiperList.value[currTabIndex.value].doLoadMore();
	}

	// 列表分页
	let page = reactive<any>({
		pageIndex: 1, // 未审核页码
		AuditPageIndex: 1, // 已审核页码
		pageSize: 10,
	});

	// 选中的排序数据 
	let sortData = ref<any>({
		OrderBy: '',
		Sort: {},
	});
	let defaultSort = ref('');
	let sortOptions = [// 排序数据
		{
			id: "1",
			name: "单据编号",
			param: 'A.BillNO',
		},
		{
			id: "2",
			name: "报工时间",
			param: 'A.ActualDate',
		}, {
			id: "3",
			name: "生产员工",
			param: 'D.EmplID',
		},
		{
			id: "4",
			name: "产品",
			param: 'B.ProductID',
		},
		{
			id: "5",
			name: "工序名称",
			param: 'B.ProcedureID',
		},
		{
			id: "6",
			name: "审核时间",
			param: 'A.ApproveTime',
		},
		{
			id: "7",
			name: "创建时间",
			param: 'B.CreateTime',
		},
		{
			id: "8",
			name: "更新时间",
			param: 'B.ModifyTime',
		}];

	// 升降序数据
	let sortFields = [
		{
			text: '升序',
			value: 'ASC'
		},
		{
			text: '降序',
			value: 'DESC'
		}
	];


	const workListDate = uni.getStorageSync('WorkListDate');
	if (workListDate) {
		const obj = JSON.parse(workListDate);

		selectData.value = obj.selectData;
		SelectDateItem = obj.SelectDateItem;
		FilterFormData.StartTime = obj.DateList[0];
		FilterFormData.EndTime = obj.DateList[1];
	}

	if (uni.getStorageSync('sortData')) { // 获取缓存的排序
		let _sortData = JSON.parse(uni.getStorageSync('sortData'));
		console.log(_sortData);

		sortData.value.OrderBy = _sortData.sortData.OrderBy;
		defaultSort.value = _sortData.defaultSort;
		sortData.value.Sort = _sortData.sortData.Sort;

	} else {
		// 无排序缓存
		// 选中排序数据
		sortData.value.OrderBy = sortOptions[0]['param'];
		defaultSort.value = sortOptions[0]['id'];
		sortData.value.Sort = sortFields[1];

		let _sortData = {
			defaultSort: defaultSort.value,
			sortData: sortData.value
		}

		uni.setStorageSync('sortData', JSON.stringify(_sortData))
	}

	setTimeout(() => {
		// 获取顶部数据
		getXGD_DailyOutputTitle();
	}, 300);

	interface sortInterface {
		open : () => void;
		close : () => void;
	};
	let popup_sort = ref<sortInterface | any>(null)

	function closeSortPopup() {	// 关闭排序弹层 
		popup_sort.value.close();
	}

	function OpenSortPopup() {	// 点击打开排序
		popup_sort.value.open();
	}

	function handleSortChange(sortDataInfo : any) { // 选中排序
		const {
			sort: {
				param,
				id
			},
			item
		} = sortDataInfo;

		closeSortPopup();

		// 在这里处理排序改变的逻辑
		setTimeout(() => {
			sortData.value.OrderBy = param;
			defaultSort.value = id;
			sortData.value.Sort = item;

			let SetInfo = {
				defaultSort: defaultSort.value,
				sortData: sortData.value,
			}
			console.log(SetInfo);
			// 写法或待更新
			uni.setStorageSync('sortData', JSON.stringify(SetInfo))
			ComfirmFilterBtn();
		}, 50);

	};

	/**
	 * 刷新页面，重新获取数据，不会清除筛选项
	 */
	function onRefresh() {
		uni.$utils.showLoading("正在加载...");
		swiperList.value[currTabIndex.value].reload(() => {
			// 获取顶部数据
			getXGD_DailyOutputTitle();
			//当当前显示的列表刷新结束，结束当前页面的刷新状态

			setTimeout(() => {
				pagePaging.value.endRefresh();
				uni.$utils.hideLoading();
			}, 500)
		});
		// 获取顶部数据
		// getXGD_DailyOutputTitle();
	}

	// 按钮样式初始化有问题，等加载完再显示
	let BtnShow = ref(false);

	function ShowTextFun(str : string, data : any) { // 显示字段的返回映射
		let backText = '';
		switch (str) {
			case 'PieceTime':
				if (uni.$utils.isEmpty(data)) {
					backText = ''
				} else {
					if (data == 0) {
						backText = '计件'
					} else if (data == 1) {
						backText = '计时'
					}
				}
				break;
			default:
				break;
		}

		return backText;
	}

	function handleRadioChange(data : any) { // 筛选弹层是否超时选项
		FilterFormData.Timeout = data.data.id;
	}

	async function getXGD_DailyOutputTitle() {	// 获取看板数据

		let FWorkshopID = FilterFormData.FWorkshopData.map((item : any) => item.FWorkshopID); // 车间
		let ProductID = FilterFormData.ProductData.map((item : any) => item.ProductID); // 物料
		let ProcedureID = FilterFormData.ProcedureData.map((item : any) => item.ProcedureID); // 工序
		let EmplID = FilterFormData.EmplData.map((item : any) => item.EmplID); // 人员

		let obj = {
			FSDate: YMDDateFormate(FilterFormData.StartTime), // 开始日期
			FEDate: YMDDateFormate(FilterFormData.EndTime), // 结束日期
			FWorkshopID: FWorkshopID.join(','), // 车间
			ProductID: ProductID.join(','), // 物料ID
			ProcedureID: ProcedureID.join(','), // 工序ID
			EmplID: EmplID.join(','), // 作业员ID
		};

		let submitCmd = 'GD_DailyOutputTitle';
		if (FCJType.value == 1) {
			submitCmd = 'XGD_DailyOutputTitle';
		} else if (FCJType.value == 2) {
			submitCmd = 'GD_DailyOutputTitle';
		}

		try {

			let result = await request({
				config: {
				},
				url: submitCmd,
				method: 'POST',
				data: obj
			});

			if (result.status != 200) {
				return;
			};

			tabList.value[0]['value'] = result.data.ds[0]['Approve0Count'];
			tabList.value[0]['badge']['count'] = result.data.ds[0]['Approve0Over24Count'];
			tabList.value[1]['value'] = result.data.ds[0]['Approve1Count'];
			console.log(tabList.value);

			KanbanListData.forEach((item, index) => {
				if (index == 0) {
					item['Value'] = result.data.ds[0]['BGDNum'];
				} else if (index == 1) {
					item['Value'] = parseFloat(result.data.ds[0]['OKRate']).toFixed(2) + '%';
				} else if (index == 2) {
					item['Value'] = result.data.ds[0]['FDailyQtt'];
				} else if (index == 3) {
					item['Value'] = result.data.ds[0]['FNgQty'];
				}
			});

		} catch (e) {
			//TODO handle the exception
		}
	}

	let routes = getCurrentPages(); //当前页面栈

	const baseScreenListenName = computed(() => {
		return 'worklist_choice_' + routes.length
	});

	function openSelectScreen(str : string) {

		switch (str) {
			case '车间':
				mainStore.openBaseScreen({
					allowClear: true,
					cmd: 'XGD_Workshop',
					titleName: str,
					listeningName: baseScreenListenName.value,
					multiple: true,
					serverSearch: {
						format: {
							displayValue: "FWorkshopName",
							hiddenValue: "FWorkshopID",
							pageIndex: "PageIndex", // 分页状态页码字段
							pageSize: "PageSize", // 分页状态每页数量字段
						},
						isPaging: true, //是否分页
						searchKey: 'SearchKey', //搜索关键词，应包含在param中
						choiceData: FilterFormData.FWorkshopData, // 选中数据
						choiceDataKey: 'FWorkshopID' // 选中数据的key
					},
					param: {
						SearchKey: '',
						PageIndex: 1,
						PageSize: 30
					}
				});
				break;
			case '物料':
				mainStore.openBaseScreen({
					allowClear: true,
					cmd: 'XGD_Product',
					titleName: str,
					listeningName: baseScreenListenName.value,
					multiple: true,
					serverSearch: {
						format: {
							displayValue: "ProductInfo",
							hiddenValue: "ProductID",
							pageIndex: "PageIndex", // 分页状态页码字段
							pageSize: "PageSize", // 分页状态每页数量字段
						},
						isPaging: true, //是否分页
						searchKey: 'EmplCode', //搜索关键词，应包含在param中
						choiceData: FilterFormData.ProductData, // 选中数据
						choiceDataKey: 'ProductID' // 选中数据的key
					},
					param: {
						SearchKey: '',
						PageIndex: 1,
						PageSize: 30
					}
				});
				break;
			case '工序':
				mainStore.openBaseScreen({
					allowClear: true,
					cmd: 'XGD_Procedure',
					titleName: str,
					listeningName: baseScreenListenName.value,
					multiple: true,
					serverSearch: {
						format: {
							displayValue: "ProcedureName",
							hiddenValue: "ProcedureID",
							pageIndex: "PageIndex", // 分页状态页码字段
							pageSize: "PageSize", // 分页状态每页数量字段
						},
						isPaging: true, //是否分页
						searchKey: 'SearchKey', //搜索关键词，应包含在param中
						choiceData: FilterFormData.ProcedureData, // 选中数据
						choiceDataKey: 'ProcedureID' // 选中数据的key
					},
					param: {
						SearchKey: '',
						PageIndex: 1,
						PageSize: 30,
					}
				});
				break;
			case '作业员':
				mainStore.openBaseScreen({
					allowClear: true,
					cmd: 'XGD_Employee',
					titleName: str,
					listeningName: baseScreenListenName.value,
					multiple: true,
					serverSearch: {
						format: {
							displayValue: "EmplName",
							hiddenValue: "EmplID",
							pageIndex: "PageIndex", // 分页状态页码字段
							pageSize: "PageSize", // 分页状态每页数量字段
						},
						isPaging: true, //是否分页
						searchKey: 'EmplCode', //搜索关键词，应包含在param中
						choiceData: FilterFormData.EmplData, // 选中数据
						choiceDataKey: 'EmplID' // 选中数据的key
					},
					param: {
						EmplCode: '',
						PageIndex: 1,
						PageSize: 30
					}
				});
				break;
			default: break;
		}

	}

	function ChoiceTime(type : string) { // 点击时间
		TimeType.value = type;
		let dates = new Date();
		if (type == 'start') {
			if (!uni.$utils.isEmpty(FilterFormData.StartTime)) {
				dates = FilterFormData.StartTime;
			}
			DatetimeData.value = Number(dates);
			PickerTitle.value = '开始时间';
		} else if (type == 'end') {
			if (!uni.$utils.isEmpty(FilterFormData.EndTime)) {
				dates = FilterFormData.EndTime;
			}
			DatetimeData.value = Number(dates);
			PickerTitle.value = '结束时间';
		} else {
			DatetimeData.value = Number(new Date());
			PickerTitle.value = '';
		}

		showTimePicker.value = true;
	}

	function dateFormat(val : string) { // 格式化时间
		if (!uni.$utils.isEmpty(val)) {
			return uni.$utils.dateFormat(new Date(val), 'Y-MM-dd');
		} else {
			return uni.$utils.dateFormat(new Date(), 'Y-MM-dd');
		}
	}

	function formatter(type : string, value : number) {	// 时间选择器数据格式化
		if (type === 'year') {
			return `${value}年`
		}
		if (type === 'month') {
			return `${value}月`
		}
		if (type === 'day') {
			return `${value}日`
		}
		if (type === 'hour') {
			return `${value}时`
		}
		if (type === 'minute') {
			return `${value}分`
		}
		return value
	}

	function ClosePicker() {	// 关闭时间选择器
		DatetimeData.value = Number(new Date());
		showTimePicker.value = false;
	}

	function ConfirmTime(data : any) {	// 确认时间
		if (TimeType.value == 'start') {

			if (!uni.$utils.isEmpty(FilterFormData.EndTime) && Number(data.value) > Number(
				FilterFormData
					.EndTime)) {
				return uni.showToast({
					title: '开始时间不能高于结束时间',
					icon: 'none'
				});
			}

			FilterFormData.StartTime = data.value;
		} else if (TimeType.value == 'end') {
			if (!uni.$utils.isEmpty(FilterFormData.StartTime) && Number(data.value) < Number(FilterFormData
				.StartTime)) {
				return uni.showToast({
					title: '结束时间不能低于开始时间',
					icon: 'none'
				});
			}
			FilterFormData.EndTime = data.value;
		}
		showTimePicker.value = false;
	}

	interface filterInterface {
		open : () => void;
		close : () => void;
	};
	let popup_filter = ref<filterInterface | any>(null)

	function rightClick() {	// 导航栏打开筛选
		popup_filter.value.open();
	}

	function closeFilterPopup() {	// 关闭筛选弹层
		popup_filter.value.close();
	}

	/**
	 * 筛选弹层重置按钮
	 */
	function ResetFilterBtn() { // 筛选弹层重置按钮

		Object.keys(FilterFormData).forEach((key) => {
			if (!['StartTime', 'EndTime'].includes(key)) {
				if (Array.isArray(FilterFormData[key])) {
					FilterFormData[key] = [];
				} else if (typeof FilterFormData[key] === 'object') {
					FilterFormData[key] = {};
				} else {
					FilterFormData[key] = '';
				}
			}
		});
		closeFilterPopup();

		onRefresh();
	}

	function ComfirmFilterBtn() {	// 筛选弹层确认按钮
		let StartDate : any;
		let EndDate : any;
		var today = new Date();

		switch (selectData.value) {
			case 0: // 今天
				StartDate = new Date();
				EndDate = new Date();
				break;
			case 1: // 昨天
				var yesterday = new Date(today);
				yesterday.setDate(today.getDate() - 1);
				StartDate = yesterday;
				EndDate = yesterday;
				break;
			case 2: // 本月
				StartDate = new Date(today.getFullYear(), today.getMonth(), 1);
				EndDate = new Date(today.getFullYear(), today.getMonth() + 1, 0);
				break;
			case 3: // 上月
				StartDate = new Date(today.getFullYear(), today.getMonth() - 1, 1);
				EndDate = new Date(today.getFullYear(), today.getMonth(), 0);
				break;
			case 4: // 全部
				// Add logic for all
				break;
			case 5: // 自定义时间
				StartDate = FilterFormData.StartTime;
				EndDate = FilterFormData.EndTime;
				break;
			default:
				break;
		};

		FilterFormData.StartTime = YMDDateFormate(StartDate);
		FilterFormData.EndTime = YMDDateFormate(EndDate);
		let DateList = [FilterFormData.StartTime, FilterFormData.EndTime];
		let DateObj = {
			DateList: DateList,
			selectData: selectData.value,
			SelectDateItem: DateList[selectData.value],
		}
		uni.setStorageSync('WorkListDate', JSON.stringify(DateObj));

		closeFilterPopup();

		onRefresh();
	}

	/** 固定转换年月日
	 * @param {*} data 时间
	 * @return {type} 如果 data 有值，返回时间字符串 ；反之返回空
	 */
	function YMDDateFormate(data : any) { // 转换年月日
		if (data) {
			var date = new Date(data);
			var year = date.getFullYear();
			var month = (date.getMonth() + 1).toString().padStart(2, '0');
			var day = date.getDate().toString().padStart(2, '0');
			var formattedDate = year + "-" + month + "-" + day;
			return formattedDate;
		} else {
			return '';
		}
	}

	function SelectDateFun(data : any, index : number) { // 时间主弹层选择时间
		selectData.value = index;
	}

	function DateComfirmBtn() { // 时间主弹层确认按钮
		SelectDateItem = DateList.value[selectData.value];
		ShowTimePopup.value = false;
	}

	function ToggleDatePopup() { // 切换选择时间弹层
		ShowTimePopup.value = !ShowTimePopup.value;
	}


	const filterConfig = computed(() => {
		let FWorkshopID = FilterFormData.FWorkshopData.map((item : any) => item.FWorkshopID); // 车间
		let ProductID = FilterFormData.ProductData.map((item : any) => item.ProductID); // 物料
		let ProcedureID = FilterFormData.ProcedureData.map((item : any) => item.ProcedureID); // 工序
		let EmplID = FilterFormData.EmplData.map((item : any) => item.EmplID); // 人员


		return {
			OrderType: sortData.value.Sort['value'], // 排序顺序  
			OrderName: sortData.value.OrderBy, // 排序字段  
			FBDate: YMDDateFormate(FilterFormData.StartTime), // 开始日期  
			FEDate: YMDDateFormate(FilterFormData.EndTime), // 结束日期  
			FWorkshopID: FWorkshopID.join(','), // 车间  
			ProductID: ProductID.join(','), // 物料ID  
			ProcedureID: ProcedureID.join(','), // 工序ID  
			EmplID: EmplID.join(','), // 作业员ID  
			FCJType: FCJType.value,
			Timeout: currTabIndex.value == 1 ? 0 : FilterFormData.Timeout
		};

	})

	// 新增报工
	function ToAddWorkBtn() {
		uni.navigateTo({
			url: '/st_ticket/page_work/work-create'
		})
	}

	let currentID = ref(-1);
	onLoad((option : any) => {
		if (!uni.$utils.isEmpty(option)) {
			currentID.value = +option.TabbarID;
		}
	});



	onReady(() => {

		uni.$on("refreshPage_works", (ret : any) => {
			onRefresh();
		});

		uni.$on(baseScreenListenName.value, (ret : any) => {
			console.log(ret);
			const { titleName } = ret;
			const dataCopy = JSON.parse(JSON.stringify(ret.data));

			switch (titleName) {
				case '车间':
					FilterFormData.FWorkshopData = dataCopy;
					FilterFormData.FWorkshopName = dataCopy.map((item : any) => item.FWorkshopName).join('、');
					break;
				case '物料':
					FilterFormData.ProductData = dataCopy;
					FilterFormData.ProductName = dataCopy.map((item : any) => item.ProductName).join('、');
					break;
				case '工序':
					FilterFormData.ProcedureData = dataCopy;
					FilterFormData.ProcedureName = dataCopy.map((item : any) => item.ProcedureName).join('、');
					break;
				case '作业员':
					FilterFormData.EmplData = dataCopy;
					FilterFormData.EmplName = dataCopy.map((item : any) => item.EmplName).join('、');
					break;
				default: break;
			}
		});
	});

	onUnload(() => {
		uni.$off("refreshPage_works");
	});
</script>

<style lang="scss" scoped>
	:deep(.uni-popup) {
		z-index: 100000 !important;
	}

	:deep(.u-tabs__wrapper__nav__item) {
		flex: initial !important;
		min-width: 100px;
	}

	.page__content {
		width: 100%;
		height: 100vh;
		background-color: #f2f2f2;
		display: flex;
		flex-direction: column;
		align-items: center;

		.icon-flip-vertical {
			display: inline-block;
			/* 或者其他适合你的布局的display值 */
			transform: scaleY(-1);
			/* 垂直翻转 */
		}

		// 顶部导航栏右侧样式
		.navRightBox {
			padding: 6rpx 8rpx;
			border-radius: 12px;
			color: #fff;
		}


		.KanbanBox {
			display: flex;
			flex-wrap: wrap;
			align-items: center;
			justify-content: space-evenly;
			background-color: #fff;

			.Kanban_CardBox {
				width: 48%;
				margin-top: 14px;
				color: #fff;
				border-radius: 12px;
				display: flex;
				flex-direction: column;
				justify-content: center;
				padding: 16rpx 0 16rpx 14rpx;
				overflow: hidden;
				position: relative;
				font-size: 12px;

				.Kanban_CardBox_Value {
					font-size: 40rpx;
					margin-top: 6rpx;
					font-weight: 600;
				}

				.Style_A {
					position: absolute;
					left: 0;
					top: 0;
					width: 24rpx;
					height: 24rpx;
					background-color: rgba(255, 255, 255, .18);
					border-radius: 0 2rpx 12rpx 0;
				}

				.Style_B {
					position: absolute;
					right: -38rpx;
					bottom: -30rpx;

					.Style_B_Round1 {
						position: relative;
						background-color: #fff;
						background-color: rgba(255, 255, 255, .15);
						width: 78rpx;
						height: 78rpx;
						border-radius: 9999px;

						.Style_B_Round2 {
							position: absolute;
							left: -20rpx;
							bottom: 14rpx;
							background-color: rgba(255, 255, 255, .15);
							width: 40rpx;
							height: 40rpx;
							border-radius: 9999px;
						}
					}
				}
			}
		}

		:deep(.u-list) {
			position: relative;
			flex: 1;
			overflow: auto;
			width: 100%;



			:deep(.u-sticky) {
				background-color: #fff !important;
				top: 0 !important;
				box-shadow: 0 8px 11px -19px;
				height: 44px;
				z-index: 1 !important;

				.u-sticky__content {
					flex: 1;
				}
			}

			.CardBox {
				position: relative;
				margin-top: 20rpx;
				background-color: #fff;
				padding: 30rpx;
				border-radius: 12px;
				// min-height: 300px;
				box-shadow: 0 0 8px -7px #333;

				.Main_Card_Top {
					display: flex;
					align-items: center;
					justify-content: space-between;

					.OrdinalBox {
						width: fit-content;
						min-width: 24px;
						height: 24px;
						border-radius: 9999px;
						background-color: #51d0d0;
						color: #fff;
						font-size: 14px;
						line-height: 24px;
						text-align: center;
					}

					.Title_Text {
						margin-left: 6px;
						font-weight: 600;
						font-size: 14px;
					}
				}

				.CommonBox {
					border-radius: 8px;
					background-color: #f7f7f7;
					padding: 10px 10px;
					margin-top: 15px;
					display: flex;
					align-items: center;
					justify-content: space-evenly;

					.TextBox {
						display: flex;
						flex-direction: column;
						align-items: center;
						flex: 1;
					}

					.BottomText {
						margin-top: 14px;
					}

					.LeftIcon {
						width: 30px;
						height: 30px;
						line-height: 30px;
						font-size: 18px;
						border-radius: 8px;
						color: #fff;
						background-color: #01b87d;
						text-align: center;
					}

					.CenterBox {
						flex: 1;
						border-radius: 8rpx;
						padding: 2rpx 10rpx;
					}
				}

			}
		}

	}


	.popup__content__main {
		&__section {
			&__content {

				// 时间选择样式
				.Select_Box {
					font-size: 24rpx;
					flex: 1;
					display: flex;
					flex-wrap: wrap;
					justify-content: space-evenly;

					.Select_Date {
						justify-content: space-between;
						padding: 6px 12px;
						background-color: #f0f0f0;
						border: 1px solid #f0f0f0;
						border-radius: 9999px;
						width: 46%;
						margin-top: 8px;
					}

					.Select_Date_Active {
						background-color: #e1f7f8 !important;
						border: 1px solid #51d0d0 !important;
						color: #51d0d0 !important;
					}

					// 起止时间
					.ChoiceTimesBox {
						width: 100%;
						display: flex;
						align-items: center;
						// background-color: #fff;
						padding: 10px 20px;
						margin-top: 6px;

						.TimeBox {
							flex: 1;
							display: flex;
							align-items: center;
							justify-content: space-evenly;
							// margin-left: 10px;

							.timer {
								width: 100%;
								flex: 2;
								display: flex;
								flex-direction: column;
								// align-items: center;
								font-size: 16px;
								color: #333;

								text:first-child {
									margin-bottom: 10px;
									font-weight: 600;
								}

								text:last-child {
									height: 20px;
								}

								.Date_Text {
									color: #999;
									font-size: 14px;
								}
							}

							.Icon {
								flex: 1;
							}
						}
					}

				}
			}
		}
	}




	// 时间选择器
	.DateTimerPick {

		.u-transition {
			z-index: 9999999 !important;
		}
	}

	// 复选框样式 start
	.uni-checkbox-input {
		border: 2px solid #d1d1d1 !important;
	}

	.uni-checkbox-input-checked {
		background: #51d0d0;
		color: #fff !important;
		border-color: #51d0d0 !important;
	}

	// 复选框样式 End
</style>